
package com.kugou.game.sdk.ui.widget;

import com.kugou.game.sdk.api.common.ActivityOrientation;
import com.kugou.game.sdk.api.common.User;
import com.kugou.game.sdk.base.BaseCommonTitleFragmentActivity;
import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.core.UserManager;
import com.kugou.game.sdk.core.VipManager;
import com.kugou.game.sdk.core.VipManager.GSInfo;
import com.kugou.game.sdk.core.VipManager.VipInfo;
import com.kugou.game.sdk.persistence.preference.PrefUtil;
import com.kugou.game.sdk.statistics.StatCmd;
import com.kugou.game.sdk.statistics.StaticsManager;
import com.kugou.game.sdk.ui.activity.CommonSdkActivity;
import com.kugou.game.sdk.ui.activity.RegisterByPhoneActivity;
import com.kugou.game.sdk.ui.fragment.SetLoginPsdFragment;
import com.kugou.game.sdk.utils.Rx;
import com.kugou.game.sdk.utils.ThreadTaskManager;
import com.kugou.game.sdk.utils.ToastUtil;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Iterator;

/**
 * 描述:悬浮窗内容适配器
 *
 * @author jerryliu
 * @since 2016年1月16日 下午5:44:26
 */
class FloatViewContentAdapter extends BaseAdapter {
    /** 悬浮窗内容角标-用户中心 */
    public static final int INDEX_USERCENTER = 0;

    /** 悬浮窗内容角标-游戏中心 */
    public static final int INDEX_GAMECENTER = 1;

    /** 悬浮窗内容角标-公告板 */
    public static final int INDEX_FORUM = 2;

    /** 悬浮窗内容角标-礼包 */
    public static final int INDEX_GIFTBAG = 3;

    /** 悬浮窗内容角标-补填密码 */
    public static final int INDEX_SETPSD = 4;

    /** 悬浮窗内容角标-VIP */
    public static final int INDEX_VIP = 5;

    ArrayList<BarInfo> data;

    Activity activity;

    private FloatView fv;

    /** 是否显示活动标签 。显示规则：显示在用户中心上，且如果活动标签和红点同时满足时，显示活动标签 */
    public boolean showActivityTag;

    /** 活动标签图标 */
    private Bitmap tagBitmap = null;

    public FloatViewContentAdapter(Activity activity, ArrayList<BarInfo> data) {
        this.data = data;
        this.activity = activity;
    }

    public void showActivityTag(Bitmap bitmap) {
        this.showActivityTag = true;
        this.tagBitmap = bitmap;
        // 标签和红点的呼吸灯逻辑是一样，所以显示活动标签时添加红点。
        if (!containsRedPoint(String.valueOf(INDEX_USERCENTER))) {
            addShowRedPoint(String.valueOf(INDEX_USERCENTER));
        }
        notifyDataSetChanged();
    }

    public void setFloatView(FloatView fv) {
        this.fv = fv;
    }

    @Override
    public int getCount() {
        return data == null ? 0 : data.size();
    }

    @Override
    public BarInfo getItem(int position) {
        if (data != null) {
            for (BarInfo info : data) {
                if (info.index == position) {
                    return info;
                }
            }
        }
        return null;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public void addData(BarInfo info) {
        if (data != null) {
            data.add(info);
        }
    }

    public void addData(int position, BarInfo info) {
        if (data != null) {
            if (position < data.size() - 1) {
                data.add(position, info);
            } else {
                data.add(info);
            }
        }
    }

    public void removeData(int index) {
        if (data != null) {
            Iterator<BarInfo> it = data.iterator();
            while (it.hasNext()) {
                BarInfo info = it.next();
                if (info.index == index) {
                    it.remove();
                }
            }
        }
    }

    public boolean isVisible(int index) {
        if (data != null) {
            for (BarInfo info : data) {
                if (info.index == index) {
                    return true;
                }
            }
        }
        return false;
    }

    // 需要显示红点的角标列表
    private ArrayList<String> points = new ArrayList<String>();

    public boolean needShowRedPoint() {
        return points != null && points.size() > 0;
    }

    public void addShowRedPoint(String index) {
        if (!points.contains(index)) {
            points.add(index);
            if (fv != null) {
                fv.setFloatViewIndicatorBackground();
                fv.startBreatheAnimation();
            }
        }
    }

    public void removeShowRedPoint(String index) {
        points.remove(index);
        // 关闭呼吸灯
        if (points.size() == 0) {
            if (fv != null) {
                fv.removeBreatheAnimation();
                fv.updateFloatViewIndicatorLayout();
            }
        }
    }

    public boolean containsRedPoint(String index) {
        return points != null && points.contains(index);
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = LayoutInflater.from(activity).inflate(
                    Rx.layout.kg_floatview_content_grid_item, null);
            holder = new ViewHolder();
            holder.layout = convertView.findViewById(Rx.id.content_item_layout);
            holder.icon = (ImageView) convertView.findViewById(Rx.id.content_item_iv);
            holder.redpoint = (ImageView) convertView.findViewById(Rx.id.content_item_red_point);
            holder.title = (TextView) convertView.findViewById(Rx.id.content_item_tv);
            holder.activityTag = (ImageView) convertView
                    .findViewById(Rx.id.content_item_activity_tag);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        final BarInfo info = data.get(position);
        holder.icon.setImageResource(info.iconResId);
        holder.layout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                handleClick(info.index);
            }
        });

        // 只在用户中心位置需要显示活动标签
        if (position == 0) {
            if (showActivityTag) {
                // 同时有标签和红点时，优先显示标签。
                holder.activityTag.setVisibility(View.VISIBLE);
                if (tagBitmap != null) {
                    holder.activityTag.setImageBitmap(tagBitmap);
                }
                holder.redpoint.setVisibility(View.GONE);
            } else {
                holder.activityTag.setVisibility(View.GONE);
                if (containsRedPoint(String.valueOf(info.index))) {
                    holder.redpoint.setVisibility(View.VISIBLE);
                } else {
                    holder.redpoint.setVisibility(View.GONE);
                }
            }
        } else {
            holder.activityTag.setVisibility(View.GONE);
            if (containsRedPoint(String.valueOf(info.index))) {
                holder.redpoint.setVisibility(View.VISIBLE);
            } else {
                holder.redpoint.setVisibility(View.GONE);
            }
        }
        holder.title.setText(info.title);
        return convertView;
    }

    protected void handleClick(int index) {
        User user = UserManager.getInstance().getCurrentUserInternal();
        switch (index) {
            case INDEX_USERCENTER:
                SDKControler.enterUserCenter(activity);
                if (containsRedPoint(String.valueOf(INDEX_USERCENTER))) {
                    // 设置当前新邮件已经提醒，可以取消红点了
                    removeShowRedPoint(String.valueOf(INDEX_USERCENTER));
                    notifyDataSetChanged();
                    fv.setFloatViewIndicatorBackground();
                }

                // 发送统计--从悬浮窗点击进入用户中心
                StaticsManager.sendCommonStatis(StatCmd.CMD_ENTER_USERCENTER_FROM_TOOLBAR);
                break;
            case INDEX_GAMECENTER:
                SDKControler.enterGameCenter(activity);
                // 取消显示红点标识
                if (containsRedPoint(String.valueOf(INDEX_GAMECENTER))) {
                    user.setGameCenterNeedRedPointRemind(false);
                    PrefUtil.setGamecenterRedpointData(activity,
                            PrefUtil.getGamecenterRedpointDataTemp(activity));

                    removeShowRedPoint(String.valueOf(INDEX_GAMECENTER));
                    notifyDataSetChanged();
                    fv.setFloatViewIndicatorBackground();
                }
                // 发送统计--从悬浮窗点击进入游戏中心
                StaticsManager.sendCommonStatis(StatCmd.CMD_ENTER_GAME_CENTER_FROM_TOOLBAR);
                break;
            case INDEX_FORUM:
                if (user != null) {
                    if (!user.isSetKugouPsd()) {
                        // 跳转到设置登录密码界面
                        activity.startActivity(CommonSdkActivity.creatIntent(activity,
                                SetLoginPsdFragment.class.getName(), Rx.string.kg_set_login_psd));
                    } else {
                        if (user.isRegistered()) {
                            SDKControler.enterGameForum(activity);
                        } else {
                            Intent intent = new Intent(activity, RegisterByPhoneActivity.class);
                            intent.putExtra(BaseCommonTitleFragmentActivity.FROM_ACTION_KEY,
                                    BaseCommonTitleFragmentActivity.FROM_FORUM);
                            activity.startActivity(intent);
                        }
                    }
                } else {
                    Intent intent = new Intent(activity, RegisterByPhoneActivity.class);
                    intent.putExtra(BaseCommonTitleFragmentActivity.FROM_ACTION_KEY,
                            BaseCommonTitleFragmentActivity.FROM_FORUM);
                    activity.startActivity(intent);
                }
                // 发送统计--悬浮窗点击论坛
                StaticsManager.sendCommonStatis(StatCmd.CMD_ENTER_FORUM_FROM_TOOLBAR);
                break;
            case INDEX_GIFTBAG:
                SDKControler.enterGiftBagCenter(activity);
                // 发送统计--从悬浮窗点击进入礼包列表
                StaticsManager.sendCommonStatis(StatCmd.CMD_ENTER_GIFTBAG_FROM_TOOLBAR);
                break;
            case INDEX_SETPSD:
                // 跳转到设置登录密码界面
                activity.startActivity(CommonSdkActivity.creatIntent(activity,
                        SetLoginPsdFragment.class.getName(), Rx.string.kg_set_login_psd));
                break;
            case INDEX_VIP:
                showVipDialog();
                break;
        }

        // 关闭悬浮窗
        ThreadTaskManager.excuteTask(new Runnable() {
            @Override
            public void run() {
                new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        fv.closeFloatView();
                    };
                }, 1000);
            }
        });
    }

    private void showVipDialog() {
        if (activity != null && !activity.isFinishing()) {
            VipInfo vipInfo = VipManager.getInstance().getVipInfo();
            if (vipInfo != null) {
                ArrayList<GSInfo> data = vipInfo.getGsInfos();
                if (data != null && data.size() > 0) {
                    int oritention = SDKControler.getOritention();
                    if (oritention == ActivityOrientation.LANDSCAPE) {
                        VipDialogLand dialogLand = new VipDialogLand(activity);
                        dialogLand.setGsListData(data);
                        dialogLand.show();
                    } else {
                        VipDialogPortrait dialogPortrait = new VipDialogPortrait(activity);
                        dialogPortrait.setGsListData(data);
                        dialogPortrait.show();
                    }
                } else {
                    ToastUtil.showMsg("暂无VIP客服信息");
                }
            }
        }
    }

    class ViewHolder {
        View layout;

        ImageView icon, redpoint, activityTag;

        TextView title;
    }
}

class BarInfo {
    int iconResId;

    String title;

    int index;
}
